package com.company.crm.workbench.service.impl;

import com.company.crm.commons.util.DateUtils;
import com.company.crm.commons.util.UUIDUtils;
import com.company.crm.settings.domain.User;
import com.company.crm.workbench.domain.Customer;
import com.company.crm.workbench.domain.Tran;
import com.company.crm.workbench.domain.TranHistory;
import com.company.crm.workbench.mapper.CustomerMapper;
import com.company.crm.workbench.mapper.TranHistoryMapper;
import com.company.crm.workbench.mapper.TranMapper;
import com.company.crm.workbench.service.TranService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

/**
 * 作者：王磊栋
 * 2021/4/25
 */
@Service
public class TranServiceImpl implements TranService {
    @Autowired
    private TranMapper tranMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private TranHistoryMapper tranHistoryMapper;
    @Override
    @Transactional( propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
    public void saveCreateTran( Map<String,Object> map) {
        User user = (User) map.get("user");
        String customerName = (String) map.get("customerName");
        Tran tran = (Tran) map.get("tran");
        tran.setId(UUIDUtils.getUUID());
        tran.setCreateBy(user.getId());
        tran.setCreateTime(DateUtils.formatDateTime(new Date()));
        //第一步：判断这个客户是否存在
        Customer customer = null;
        if (customerName==null||customerName.trim().length()==0){
            customer = new Customer();
            customer.setId(UUIDUtils.getUUID());
            customer.setOwner(user.getId());
            customer.setName(customerName);
            customer.setNextContactTime(tran.getNextContactTime());
            customer.setCreateBy(user.getId());
            customer.setCreateTime(DateUtils.formatDateTime(new Date()));
            customerMapper.insertCustomer(customer);
            tran.setCustomerId(customer.getId());
        }
        //第二步：保存完之后，向交易表中插入
        tranMapper.insertTran(tran);
        //第三步：交易历史也应该插入一条数据
        TranHistory tranHistory = new TranHistory();
        tranHistory.setId(UUIDUtils.getUUID());
        tranHistory.setStage(tran.getStage());
        tranHistory.setMoney(tran.getMoney());
        tranHistory.setExpectedDate(tran.getExpectedDate());
        tranHistory.setCreateBy(user.getId());
        tranHistory.setCreateTime(DateUtils.formatDateTime(new Date()));
        tranHistory.setTranId(tran.getId());
        tranHistoryMapper.insertTranHistory(tranHistory);
    }

    @Override
    public Tran selectTranDetailByTranId(String id) {
        return tranMapper.selectTranForDetailById(id);
    }
}
